﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MyBlog.Model;

namespace MyBlog.Common
{
    /// <summary>
    /// 表示修饰的方法需要授权才能执行
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthenticateAttribute : AuthorizeAttribute
    {
        bool _isAuthenticate = true;
        public AuthenticateAttribute()
        { }

        /// <summary>
        /// 初始化身份验证
        /// </summary>
        /// <param name="isAuthenticate">默认为true，表示完全授权增删改操作；如果为false，则只需要验证是否登入</param>
        public AuthenticateAttribute(bool isAuthenticate)
        {
            _isAuthenticate = isAuthenticate;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!_isAuthenticate)//不需要进行身份验证
            {
                if (filterContext.HttpContext.Session["loginUser"] != null)
                {
                    return;
                }
            }
            else
            {
                if (!filterContext.RouteData.Values.ContainsKey("username") || filterContext.RouteData.Values["username"] == null
                    || string.IsNullOrWhiteSpace(filterContext.RouteData.Values["username"].ToString()))
                {
                    throw new ApplicationException(ErrorMsg.NotFound);
                }
                if (filterContext.HttpContext.Session["loginUser"] != null
                    && filterContext.HttpContext.Request.IsAuthenticated
                    && !string.IsNullOrWhiteSpace(filterContext.HttpContext.User.Identity.Name)
                    && filterContext.RouteData.Values["username"].ToString().Same(filterContext.HttpContext.User.Identity.Name))
                {
                    return;
                }
            }
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = new JsonData
                    {
                        State = AjaxState.Fail,
                        Message = _isAuthenticate ? "会话已过期，请重新登录！" : "您还没有登录哦！",
                        Url = FormsAuthentication.LoginUrl
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                string warningTip;
                if (filterContext.HttpContext.Session["loginUser"] == null && filterContext.HttpContext.Request.IsAuthenticated
                    && filterContext.RouteData.Values["username"].ToString().Same(filterContext.HttpContext.User.Identity.Name))
                {
                    warningTip = "<script lauguage='Javascript'>alert('会话已过期，请重新登录！');window.location.href='"
                               + filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority)
                               + "/Account/login?ReturnUrl=" + HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString()) + "';</script>";
                }
                else
                {
                    if (filterContext.HttpContext.Session["loginUser"] != null && filterContext.HttpContext.Request.IsAuthenticated
                    && !filterContext.RouteData.Values["username"].ToString().Same(filterContext.HttpContext.User.Identity.Name))
                    {
                        warningTip = "<script lauguage='Javascript'>alert('咳咳，这是非法操作！');window.location.href='"
                               + filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority)
                               + "/Account/login';</script>";
                    }
                    else
                    {
                        warningTip = "<script lauguage='Javascript'>alert('你需要登录才能执行此操作！');window.location.href='"
                                    + filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority)
                                    + "/Account/login?ReturnUrl=" + HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString()) + "';</script>";
                    }
                }
                filterContext.Result = new ContentResult { Content = warningTip };
            }

            //不调用默认的form验证
            //base.OnAuthorization(filterContext);
        }
    }
}
